package jnpf.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.exception.DataException;
import jnpf.permission.entity.UserEntity;
import jnpf.service.*;
import jnpf.entity.*;
import jnpf.util.*;
import jnpf.model.relation.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.*;
import jnpf.annotation.JnpfField;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.base.vo.DownloadVO;
import jnpf.config.ConfigValueUtil;
import jnpf.base.entity.ProvinceEntity;
import java.io.IOException;
import java.util.stream.Collectors;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.exception.WorkFlowException;
import org.springframework.transaction.annotation.Transactional;

/**
 * relation
 * @版本： V3.5
 * @版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * @作者： JNPF开发平台组
 * @日期： 2025-04-11
 */
@Slf4j
@RestController
@Tag(name = "relation" , description = "example")
@RequestMapping("/api/example/Relation")
public class RelationController {

    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private RelationService relationService;

    @Autowired
    private RelationContentService relationContentService;


    /**
    * 列表
    *
    * @param relationPagination
    * @return
    */
    @Operation(summary = "获取列表")
    @PostMapping("/getList")
    public ActionResult list(@RequestBody RelationPagination relationPagination)throws IOException{
        List<RelationEntity> list= relationService.getList(relationPagination);
        List<Map<String, Object>> realList=new ArrayList<>();
        for (RelationEntity entity : list) {
        Map<String, Object> relationMap=JsonUtil.entityToMap(entity);
        relationMap.put("id", relationMap.get("id"));
        //副表数据
        //子表数据
        List<RelationContentEntity> relationContentList = relationService.getRelationContentList(entity.getId(),relationPagination);
        relationMap.put("tableField104",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(relationContentList)));
            realList.add(relationMap);
        }
        //数据转换
        realList = generaterSwapUtil.swapDataList(realList, RelationConstant.getFormData(), RelationConstant.getColumnData(), relationPagination.getModuleId(),false);

        //返回对象
        PageListVO vo = new PageListVO();
        vo.setList(realList);
        PaginationVO page = JsonUtil.getJsonToBean(relationPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }

    /**
     * 查询当前分类id下的所有关系
     * @param id
     * @return
     */
    @Operation(summary = "查询当前分类id下关联数量")
    @GetMapping("/getRalationSize/{id}")
    public ActionResult getTypeList(@PathVariable("id") String id){
        List<RelationContentEntity> relationContentList1 = relationService.getRelationContentList(id);
        return ActionResult.success(relationContentList1.size());
    }



    /**
    * 创建
    *
    * @param relationForm
    * @return
    */
    @PostMapping("/create")
    @Operation(summary = "创建")
    public ActionResult create(@RequestBody @Valid RelationForm relationForm) {
        String b = relationService.checkForm(relationForm,0);
        if (StringUtil.isNotEmpty(b)){
            return ActionResult.fail(b );
        }
        try{
            relationService.saveOrUpdate(relationForm, null ,true);
        }catch(Exception e){
            return ActionResult.fail("新增数据失败");
        }
        return ActionResult.success("创建成功");
    }
    /**
    * 批量删除
    * @param ids
    * @return
    */
    @DeleteMapping("/batchRemove")
    @Transactional
    @Operation(summary = "批量删除")
    public ActionResult batchRemove(@RequestBody String ids){
        List<String> idList = JsonUtil.getJsonToList(ids, String.class);
        int i =0;
        for (String allId : idList){
            this.delete(allId);
            i++;
        }
        if (i == 0 ){
        return ActionResult.fail("删除失败");
        }
        return ActionResult.success("删除成功");
    }
    /**
    * 编辑
    * @param id
    * @param relationForm
    * @return
    */
    @PutMapping("/{id}")
    @Operation(summary = "更新")
    public ActionResult update(@PathVariable("id") String id,@RequestBody @Valid RelationForm relationForm,
                                @RequestParam(value = "isImport", required = false) boolean isImport){
        relationForm.setId(id);
        if (!isImport) {
            String b =  relationService.checkForm(relationForm,1);
            if (StringUtil.isNotEmpty(b)){
                return ActionResult.fail(b );
            }
        }
        RelationEntity entity= relationService.getInfo(id);
        if(entity!=null){
            try{
                relationService.saveOrUpdate(relationForm,id,false);
            }catch(Exception e){
                return ActionResult.fail("修改数据失败");
            }
            return ActionResult.success("更新成功");
        }else{
            return ActionResult.fail("更新失败，数据不存在");
        }
    }
    /**
    * 删除
    * @param id
    * @return
    */
    @Operation(summary = "删除")
    @DeleteMapping("/delete/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id){
        RelationEntity entity= relationService.getInfo(id);
        if(entity!=null){
            //主表数据删除
            relationService.delete(entity);
            QueryWrapper<RelationContentEntity> queryWrapperRelationContent=new QueryWrapper<>();
            queryWrapperRelationContent.lambda().eq(RelationContentEntity::getRelationId,entity.getId());
            //子表数据删除
            relationContentService.remove(queryWrapperRelationContent);
        }
        return ActionResult.success("删除成功");
    }
    /**
    * 表单信息(详情页)
    * 详情页面使用-转换数据
    * @param id
    * @return
    */
    @Operation(summary = "表单信息(详情页)")
    @GetMapping("/detail/{id}")
    public ActionResult detailInfo(@PathVariable("id") String id){
        RelationEntity entity= relationService.getInfo(id);
        if(entity==null){
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> relationMap=JsonUtil.entityToMap(entity);
        relationMap.put("id", relationMap.get("id"));
        //副表数据
        //子表数据
        List<RelationContentEntity> relationContentList = relationService.getRelationContentList(entity.getId());
        relationMap.put("tableField104",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(relationContentList)));
        relationMap = generaterSwapUtil.swapDataDetail(relationMap,RelationConstant.getFormData(),"679757625272832837",false);
        return ActionResult.success(relationMap);
    }
    /**
    * 获取详情(编辑页)
    * 编辑页面使用-不转换数据
    * @param id
    * @return
    */
    @Operation(summary = "信息")
    @GetMapping("/{id}")
    public ActionResult info(@PathVariable("id") String id){
        RelationEntity entity= relationService.getInfo(id);
        if(entity==null){
            return ActionResult.fail("表单数据不存在！");
        }
        Map<String, Object> relationMap=JsonUtil.entityToMap(entity);
        relationMap.put("id", relationMap.get("id"));
        //副表数据
        //子表数据
        List<RelationContentEntity> relationContentList = relationService.getRelationContentList(entity.getId());
        relationMap.put("relationContentList",JsonUtil.getJsonToList(JsonUtil.getListToJsonArray(relationContentList)));
        relationMap = generaterSwapUtil.swapDataForm(relationMap,RelationConstant.getFormData(),RelationConstant.TABLEFIELDKEY,RelationConstant.TABLERENAMES);
        return ActionResult.success(relationMap);
    }

}
